package top.wilsonlv.jaguar.cloud.websocket.task;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import top.wilsonlv.jaguar.cloud.websocket.handler.WebsocketOnlineHandler;
import top.wilsonlv.jaguar.cloud.websocket.properties.WebsocketProperties;
import top.wilsonlv.jaguar.cloud.websocket.wrapper.WebsocketSessionWrapper;

import java.time.LocalDateTime;

/**
 * @author lvws
 * @since 2021/12/30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WebsocketTaskSchedule {

    private final WebsocketProperties websocketProperties;

    private final WebsocketOnlineHandler websocketOnlineHandler;

    @Scheduled(initialDelay = 5000, fixedRate = 5000)
    public void pong() {
        int checkTime = websocketProperties.getHeartBeatRate() + websocketProperties.getExpireTime() - websocketProperties.getExpireCheckTime();
        LocalDateTime expireTime = LocalDateTime.now().plusSeconds(-checkTime);
        for (WebsocketSessionWrapper session : WebsocketOnlineHandler.getWsSessionIdMapping().values()) {
            if (session.getLastHeartBeatTime().isBefore(expireTime)) {
                if (session.pong()) {
                    websocketOnlineHandler.saveConnection(session, null);
                }
            }
        }
    }

}
